package net.howson.phil.datahiding.scheme;

import java.util.Random;

public class DefaultSingleValueEncodingScheme implements
		SingleValueEncodingScheme {

	private final Random seededRandom;
	private final Random unseededRandom;

	public DefaultSingleValueEncodingScheme(int randomSeed) {
		this.seededRandom = new Random(randomSeed);
		this.unseededRandom = new Random();
	}

	@Override
	public int decode(int input, int seed) {
		int diff;
		if (input < seed) {
			diff = seed - input;
		} else {
			diff = input - seed;
		}

		return diff ^ seededRandom.nextInt(16);
	}

	@Override
	public int encode(int input, int existing) {
		input ^= seededRandom.nextInt(16);
		if (existing < 16) {
			existing += input;
		} else if (existing > 239) {
			existing -= input;
		} else if (unseededRandom.nextBoolean()) {
			existing -= input;
		} else {
			existing += input;
		}

		return existing;
	}

	@Override
	public int getNumberOfBytesEncodable(int width, int height) {
		return (width * height * 3) / 2;
	}

}
